<template>
  <div
    v-if="node.type === 'start' || node.type === 'end' || node.type === 'event'"
    :id="node.id"
    :class="{
      active: isActive(),
      isStart: node.type === 'start',
      isEnd: node.type === 'end',
    }"
    :style="{
      top: node.y + 'px',
      left: node.x + 'px',
      cursor: setCursor(currentTool.type),
    }"
    class="common-circle-node"
    @click.stop="selectNode"
    @contextmenu.stop="showNodeContextMenu"
  >
    {{ node.nodeName }}
  </div>

  <a-tooltip
    @visibleChange="visibleChange($event, node)"
    placement="bottom"
    v-else-if="
      node.type === 'MeasurementControlBaseband' ||
      node.type === 'singleChannelDownConverter' ||
      node.type === 'controlEquipment' ||
      node.type === 'exchangeBoard' ||
      node.type === 'accessAuthentication' ||
      node.type === 'hornAntenna' ||
      node.type === 'QBandDownconverter' ||
      node.type === 'VBandUpconverter' ||
      node.type === 'ProtocolGateway' ||
      node.type === 'feedBaseband' ||
      node.type === 'switchMatrix' ||
      node.type === 'commone' ||
      node.type === 'commonf' ||
      node.type === 'commong' ||
      node.type === 'freedom' ||
      node.type === 'child-flow'||
      node.type === 'BCode'
    "
  >
    <template slot="title">
      <p>设置id：{{ node.infoAll ? node.infoAll.deviceId : '' }}</p>
      <p>设置名称：{{ node.infoAll ? node.infoAll.name : '' }}</p>
      <p>设置类型：{{ node.infoAll ? node.infoAll.type : '' }}</p>
      <p>设备ip：{{ node.infoAll ? node.infoAll.ip : '' }}</p>
      <p>所属单位：{{ node.infoAll ? node.infoAll.departments : '' }}</p>
      <p>位置信息：{{ node.infoAll ? node.infoAll.position : '' }}</p>
      <p>设备生产商：{{ node.infoAll ? node.infoAll.manufacturer : '' }}</p>
    </template>
    <vdr
      :draggable="false"
      :resizable="false"
      :w="60"
      :h="60"
      :min-width="60"
      :min-height="60"
      :handles="['mr', 'br', 'bm']"
      :id="node.id"
      :class="{ active: isActive() }"
      :style="{
        top: node.y + 'px',
        left: node.x + 'px',
        cursor: setCursor(currentTool.type),
        border: filterBorderColor(node),
      }"
      class="common-rectangle-node"
      @resizing="onResize"
      @resizestop="onResizeStop"
    >
      <div class="inner-box" @click.stop="selectNode" @contextmenu.stop="showNodeContextMenu">
        <span v-if="['port', 'unport'].includes(node.icon)" @click.stop class="node-mvc-port-tit"
          >端口{{ node.name }}</span
        >
        <div v-else class="node-mvc-port-tit" @click.stop>
          <a-input placeholder="请输入" @blur="node.showInput = false" v-if="node.showInput" v-model="node.nodeName" />
          <span v-else @dblclick="node.showInput = true">
            {{ node.nodeName }}
          </span>
        </div>

        <img v-show="node.icon === 'NE40'" :src="mvc.ne40e" class="node-mvc" alt />
        <img v-show="node.icon === 'S5700'" :src="mvc.s5700" class="node-mvc" alt />
        <img v-show="node.icon === 'USG5500'" :src="mvc.usg5500" class="node-mvc" alt />
        <img v-show="node.icon === 'tcpK'" :src="mvc.tcpK" class="node-mvc" alt />
        <img v-show="node.icon === 'tcpF'" :src="mvc.tcpF" class="node-mvc" alt />
        <img v-show="node.icon === 'udpOdd'" :src="mvc.udpOdd" class="node-mvc" alt />
        <img v-show="node.icon === 'udpMore'" :src="mvc.udpMore" class="node-mvc" alt />
        <img v-show="node.icon === 'frequency'" :src="mvc.frequency" class="node-mvc" alt />
        <img v-show="node.icon === 'port'" :src="mvc.port" class="node-mvc-port" alt />
        <img v-show="node.icon === 'unport'" :src="mvc.port" class="node-mvc-ports" alt />
        <img v-show="node.icon === 'laBa'" :src="mvc.laBa" class="node-mvc-ports" alt />
        <img v-show="node.icon === 'BCode'" :src="mvc.bCode" class="node-mvc" alt />
      </div>
    </vdr>
  </a-tooltip>

  <div
    v-else-if="node.type === 'gateway'"
    :id="node.id"
    :class="{ active: isActive() }"
    :style="{
      top: node.y + 'px',
      left: node.x + 'px',
      cursor: setCursor(currentTool.type),
    }"
    class="common-diamond-node"
    @click.stop="selectNode"
    @contextmenu.stop="showNodeContextMenu"
  />

  <div
    v-else-if="node.type === 'x-lane'"
    :id="node.id"
    :class="{ active: isActive() }"
    :style="{
      top: node.y + 'px',
      left: node.x + 'px',
      height: node.height + 'px',
      width: node.width + 'px',
    }"
    class="common-x-lane-node"
  >
    <div
      :style="{ cursor: setCursor(currentTool.type) }"
      class="lane-text-div"
      @click.stop="selectNode"
      @contextmenu.stop="showNodeContextMenu"
    >
      <span class="lane-text">{{ node.nodeName }}</span>
    </div>
  </div>

  <div
    v-else-if="node.type === 'y-lane'"
    :id="node.id"
    :class="{ active: isActive() }"
    :style="{
      top: node.y + 'px',
      left: node.x + 'px',
      height: node.height + 'px',
      width: node.width + 'px',
    }"
    class="common-y-lane-node"
  >
    <div
      :style="{ cursor: setCursor(currentTool.type) }"
      class="lane-text-div"
      @click.stop="selectNode"
      @contextmenu.stop="showNodeContextMenu"
    >
      <span class="lane-text">{{ node.nodeName }}</span>
    </div>
  </div>

  <div v-else />
</template>

<script>
import { Resizable } from 'resizable-dom'
import vdr from 'vue-draggable-resizable-gorkys'
import 'vue-draggable-resizable-gorkys/dist/VueDraggableResizable.css'
import { httpAction, getAction } from '@api/manage'

export default {
  components: {
    vdr,
  },
  props: {
    select: {
      type: Object,
      default: () => ({}),
    },
    selectGroup: {
      type: Array,
      default: () => [],
    },
    node: {
      type: Object,
      default: () => ({}),
    },
    plumb: {
      type: Object,
      default: () => ({}),
    },
    currentTool: {
      type: Object,
      default: () => ({}),
    },
    flowConfig: {
      type: Object,
      default: () => ({}),
    },
    dragable: {
      type: Boolean,
      default: true,
    },
  },
  // eslint-disable-next-line vue/require-prop-types
  // props: ['select', 'selectGroup', 'node', 'plumb', 'currentTool', 'flowConfig', 'dragable'],
  data() {
    return {
      resizing: false,
      width: 0,
      height: 0,
      currentSelect: this.select,
      currentSelectGroup: this.selectGroup,
      mvc: {
        // ne40e: require('../assets/mvc/ne40e.png'),
        // s5700: require('../assets/mvc/s5700.png'),
        // usg5500: require('../assets/mvc/usg5500.png'),
        // tcpK: require('../assets/mvc/tcpK.png'),
        // tcpF: require('../assets/mvc/tcpF.png'),
        // udpOdd: require('../assets/mvc/udpOdd.jpg'),
        // udpMore: require('../assets/mvc/udpMore.jpg'),
        // frequency: require('../assets/mvc/frequency.png'),
        // port: require('../assets/mvc/port.png'),
        bCode:require('../assets/mvc/BCode.png'),
        ne40e: require('../assets/mvc/测控基带设备.jpg'),
        s5700: require('../assets/mvc/单通道下变频器.jpg'),
        usg5500: require('../assets/mvc/Q频段下变频器.jpg'),
        tcpK: require('../assets/mvc/V频段上变频器.jpg'),
        tcpF: require('../assets/mvc/协议网关.jpg'),
        udpOdd: require('../assets/mvc/馈电基带设备.jpg'),
        udpMore: require('../assets/mvc/中频开关矩阵.jpg'),
        frequency: require('../assets/mvc/frequency.png'),
        port: require('../assets/mvc/port.png'),
        laBa: require('../assets/mvc/labatianxian.jpg'),
      },
    }
  },
  watch: {
    select(val) {
      this.currentSelect = val
    },
    currentSelect: {
      handler(val) {
        this.$emit('update:select', val)
      },
      deep: true,
    },
    selectGroup(val) {
      this.currentSelectGroup = val
    },
    currentSelectGroup: {
      handler(val) {
        this.$emit('update:selectGroup', val)
      },
      deep: true,
    },
  },
  mounted() {
    this.registerNode()
  },
  methods: {
    filterBorderColor(node) {
      // 开启
      if (node.onlineState === 'online') {
        return '4px solid #67c23a'
      }
      // 关闭
      if (node.onlineState === 'offline') {
        return '4px solid #bfbfbf'
      }
      // 告警
      if (node.onlineState === 'alarm') {
        return '4px solid #f56c6c'
      }
    },
    visibleChange(visible, node) {
      // getAction(`/device/dmDevice/getByTopologyInstId`, { topologyInstId: node.id }).then((res) => {
      //   if (res.success) {
      //     node.infoAll = res.result
      //     this.$forceUpdate()
      //   } else {
      //     this.$message.warning(res.message)
      //   }
      // })
    },
    onResize(left, top, width, height) {
      this.resizing = true
      this.width = width
      this.height = height
      this.$emit('onResize', true)
    },
    onResizeStop(x, y, width, height) {
      this.resizing = false
    },
    // 设置ICON
    setIcon(type) {
      switch (type) {
        case 'common':
          return 'user'
        case 'freedom':
          return 'sync'
        case 'child-flow':
          return 'apartment'
        default:
          return 'tool'
      }
    },
    // 设置鼠标样式
    setCursor(type) {
      switch (type) {
        case 'drag':
          return 'move'
        case 'connection':
          return 'crosshair'
        default:
          return 'default'
      }
    },
    // 初始节点拖拽
    registerNode() {
      console.log(this.dragable, 'dragable')
      if (!this.dragable) return
      this.plumb.draggable(this.node.id, {
        containment: 'parent',
        handle: (e, el) => {
          // 判断节点类型
          const possibles = el.parentNode.querySelectorAll(
            '.common-circle-node,.common-rectangle-node,.common-diamond-node,.lane-text-div'
          )
          for (let i = 0; i < possibles.length; i++) {
            if (possibles[i] === el || e.target.className === 'lane-text') return true
          }
          return false
        },
        grid: this.flowConfig.defaultStyle.alignGridPX,
        drag: (e) => {
          if (this.flowConfig.defaultStyle.isOpenAuxiliaryLine) {
            this.$emit('alignForLine', e)
          }
        },
        stop: (e) => {
          this.node.x = e.pos[0]
          this.node.y = e.pos[1]
          this.$emit('nodeInfo', this.node)
          // 是否为组
          if (this.currentSelectGroup.length > 1) {
            // 更新组节点信息
            this.$emit('updateNodePos')
          }
          // 隐藏辅助线
          this.$emit('hideAlignLine')
        },
      })

      if (this.node.type === 'x-lane' || this.node.type === 'y-lane') {
        const node = document.querySelector('#' + this.node.id)
        new Resizable(
          node,
          {
            handles: ['e', 'w', 'n', 's', 'nw', 'ne', 'sw', 'se'],
            initSize: {
              maxWidth: 1000,
              maxHeight: 1000,
              minWidth: 200,
              minHeight: 200,
            },
          },
          () => {
            this.node.height = Math.ceil(parseInt(node.style.height))
            this.node.width = Math.ceil(parseInt(node.style.width))
          }
        )
      }
      this.currentSelect = this.node
      this.currentSelectGroup = []
    },
    // 点击节点
    selectNode() {
      this.currentSelect = this.node
      this.$emit('isMultiple', (flag) => {
        if (!flag) {
          this.currentSelectGroup = []
        } else {
          const f = this.currentSelectGroup.find((s) => s.id === this.node.id)
          if (!f) {
            this.plumb.addToDragSelection(this.node.id)
            this.currentSelectGroup.push(this.node)
          }
        }
      })

      this.$emit('leftClickNode', this.currentSelect)
    },
    // 节点右键
    showNodeContextMenu(e) {
      e.id = this.node.vmDeviceId
      this.selectNode()
      this.$emit('showNodeContextMenu', e, this.currentSelect)
    },
    // 节点是否激活
    isActive() {
      if (this.currentSelect.id === this.node.id) return true
      return !!this.currentSelectGroup.find((n) => n.id === this.node.id)
    },
  },
}
</script>
<style lang="less" scoped>
.node-mvc {
  width: 50px;
  height: 50px;
  display: block;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
.node-mvc-port {
  width: 50px;
  height: 50px;
  display: block;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
.node-mvc-ports {
  width: 50px;
  height: 50px;
  display: block;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: #aaa;
  cursor: not-allowed;
}
.node-mvc-port-tit {
  width: 100%;
  font-size: 12px;
  text-align: center;
  display: block;
  margin-top: -2px;
  position: absolute;
  top: -26px;
}
.common-rectangle-node {
  padding: 0px;
}
.inner-box {
  width: 100%;
  height: 100%;
  position: relative;
}
</style>
<style>
#flowContainer .handle-mr {
  top: 66% !important;
  border-radius: 50%;
}
#flowContainer .handle-bm {
  left: 66% !important;
  border-radius: 50%;
}
#flowContainer .handle-br {
  border-radius: 50%;
}
</style>
